/* eslint-disable */
import React, { useEffect, useState } from 'react';
import { Avatar, Card, Form, Input, Button, Space, Upload, message, Tabs, Divider, Select } from "antd";
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useNavigate } from 'react-router-dom'; 

const { TabPane } = Tabs;

const TeacherProfile = () => {
    const [teacher, setTeacher] = useState({});
    const [originalTeacher, setOriginalTeacher] = useState({}); // 保存原始数据
    const [isEditing, setIsEditing] = useState(false);
    const [avatarUrl, setAvatarUrl] = useState(require("../../assets/images/photo.jpg")); // 默认头像
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [oldPassword, setOldPassword] = useState(''); // 新增原密码字段

    const [numberError, setNumberError] = useState('');
    const [phoneError, setPhoneError] = useState('');
    const [oldPasswordError, setOldPasswordError] = useState('');
    const [newPasswordError, setNewPasswordError] = useState('');

    const Navigate = useNavigate(); 

    // 获取教师数据
    useEffect(() => {
        fetchTeacherData();
    }, []);

    // 获取教师数据
    const fetchTeacherData = () => {
        const token = localStorage.getItem('token');
        axios.get('http://47.111.104.30:8080/api/v2/teachers/me', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                const teacherData = response.data;
                console.log('Received teacher data:', teacherData); // 添加日志
                // 处理日期格式
                if (teacherData.birthDate) {
                    teacherData.birthDate = new Date(teacherData.birthDate).toISOString().split('T')[0];
                }
                // 确保电话号码字段存在
                if (teacherData.phone === undefined) {
                    teacherData.phone = '';
                }
                setTeacher(teacherData);
                setOriginalTeacher(teacherData); // 保存原始数据
            })
            .catch(error => {
                console.error('Error fetching teacher data:', error);
                message.error('获取数据失败');
            });
    };

    // 处理文件上传（本地路径）
    const handleUpload = (info) => {
        if (info.file.status === 'done') {
            const reader = new FileReader();
            reader.onload = (e) => {
                setAvatarUrl(e.target.result);
            };
            reader.readAsDataURL(info.file.originFileObj);
            message.success('头像上传成功');
        } else if (info.file.status === 'error') {
            message.error('头像上传失败');
        }
    };

    // 保存个人信息
    const handleSave = () => {
        const numberValidation = validateNumber(teacher.number);
        const phoneValidation = validatePhone(teacher.phone);

        if (numberValidation || phoneValidation) {
            setNumberError(numberValidation);
            setPhoneError(phoneValidation);
            message.error('请检查输入信息是否正确');
            return;
        }

        const token = localStorage.getItem('token');
        const updatedTeacher = {
            ...teacher,
            birthDate: teacher.birthDate ? new Date(teacher.birthDate).toISOString().split('T')[0] : null
        };

        axios.put(`http://47.111.104.30:8080/api/v2/teachers/${teacher.id}`, updatedTeacher, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                message.success('修改成功');
                setIsEditing(false);
                fetchTeacherData();
            })
            .catch(error => {
                console.error('Error saving teacher information:', error);
                message.error('信息保存失败');
            });
    };

    // 验证工号
    const validateNumber = (value) => {
        if (!value) {
            return '工号不能为空';
        }
        if (!/^\d+$/.test(value)) {
            return '工号必须为数字';
        }
        return '';
    };

    // 验证电话号码
    const validatePhone = (value) => {
        if (!value) {
            return '电话号码不能为空';
        }
        if (!/^\d+$/.test(value)) {
            return '电话号码必须为数字';
        }
        if (value.length !== 11) {
            return '电话号码必须为11位';
        }
        return '';
    };

    //验证新密码强度
    const validateNewPassword = (password) => {
        if (!password) {
            return '新密码不能为空';
        }

        const hasUpperCase = /[A-Z]/.test(password);
        const hasLowerCase = /[a-z]/.test(password);
        const hasNumbers = /\d/.test(password);
        const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
        const isLongEnough = password.length >= 8;

        if (!isLongEnough || !hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChar) {
            return '密码不符合要求';
        }

        return '';
    };

    // 取消编辑
    const handleCancel = () => {
        setTeacher(originalTeacher); // 恢复到原始数据
        setIsEditing(false);
        setNumberError(''); // 重置工号校验错误
        setPhoneError(''); // 重置电话号码校验错误
    };

    // 处理输入变化
    const handleChange = (e) => {
        const { name, value } = e.target;

        if (name === 'number') {
            const error = validateNumber(value);
            setNumberError(error);
        }

        if (name === 'phone') {
            const error = validatePhone(value);
            setPhoneError(error);
        }

        setTeacher(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    // 修改密码处理函数
    const handlePasswordChange = () => {
        // 验证旧密码
        if (!oldPassword) {
            setOldPasswordError('旧密码不能为空');
            return;
        }

        // 验证新密码
        const newPasswordValidation = validateNewPassword(newPassword);
        if (newPasswordValidation) {
            setNewPasswordError(newPasswordValidation);
            return;
        }

        // 验证确认密码
        if (newPassword !== confirmPassword) {
            message.error('两次输入的密码不一致');
            return;
        }

        const token = localStorage.getItem('token');
        axios.put(`http://47.111.104.30:8080/api/v2/teachers/${teacher.id}/password`, { oldPassword, newPassword }, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                message.success('密码修改成功，请重新登录');
                setTimeout(() => {
                    localStorage.removeItem('token');
                    Navigate('/login'); 
                }, 1000); 
            })
            .catch(error => {
                console.error('Error changing password:', error);
                message.error('密码修改失败');
            });
    };

    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-start', minHeight: 'calc(100vh - 64px)', padding: '24px' ,marginTop:"-20px",height:"100%"}}>
            <Card style={{ width: '800px', height: '600px', width: '100%' }}>
                <Tabs tabPosition="left" style={{ height: '100%' }}>
                    {/* 个人信息界面 */}
                    <TabPane tab="个人信息" key="1">
                        <div style={{ height: '100%', display: 'flex', flexDirection: 'row', marginTop: '60px' }}>
                            {/* 左侧头像 */}
                            <div style={{ width: '30%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    showUploadList={false}
                                    beforeUpload={() => false} // 阻止自动上传
                                    onChange={handleUpload}
                                >
                                    {avatarUrl ? (
                                        <img src={avatarUrl} alt="avatar" style={{ width: '150px', height: '150px', borderRadius: '50%' }} />
                                    ) : (
                                        <UploadOutlined style={{ fontSize: '32px' }} />
                                    )}
                                </Upload>
                            </div>
                            <Divider type="vertical" style={{ height: '100%' }} />
                            {/* 右侧信息 */}
                            <div style={{ width: '70%', display: 'flex', flexDirection: 'column' }}>
                                <Form layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                    <Form.Item label="姓  名">
                                        <Input
                                            name="name"
                                            placeholder="请输入姓名"
                                            value={teacher.name}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                            maxLength={20}
                                            showCount={true}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        label="工  号"
                                        validateStatus={numberError ? 'error' : ''}
                                        help={numberError}
                                    >
                                        <Input
                                            name="number"
                                            placeholder="请输入工号"
                                            value={teacher.number}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item label="性  别">
                                        <Select
                                            name="gender"
                                            placeholder="请选择性别"
                                            value={teacher.gender}
                                            onChange={(value) => handleChange({ target: { name: 'gender', value } })}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        >
                                            <Select.Option value="男">男</Select.Option>
                                            <Select.Option value="女">女</Select.Option>
                                        </Select>
                                    </Form.Item>
                                    <Form.Item label="出生日期">
                                        <Input
                                            name="birthDate"
                                            type="date"
                                            placeholder="请输入出生日期"
                                            value={teacher.birthDate || ''}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item label="学  院">
                                        <Input
                                            name="college"
                                            placeholder="请输入学院"
                                            value={teacher.college}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        label="联系方式"
                                        validateStatus={phoneError ? 'error' : ''}
                                        help={phoneError}
                                    >
                                        <Input
                                            name="phone"
                                            placeholder="请输入联系方式"
                                            value={teacher.phone}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item label="地  址">
                                        <Input
                                            name="address"
                                            placeholder="请输入地址"
                                            value={teacher.address}
                                            onChange={handleChange}
                                            disabled={!isEditing}
                                            style={{ height: '30px', width: '50%' }}
                                        />
                                    </Form.Item>
                                </Form>


                                <Space style={{ marginTop: 'auto', marginBottom: 24, marginTop: "20px" }}>
                                    {isEditing ? (
                                        <>
                                            <Button type="primary" onClick={handleSave} style={{ marginLeft: "250px", marginTop: "10px" }}>保存</Button>
                                            <Button onClick={handleCancel} style={{ marginLeft: "30px", marginTop: "10px" }}>取消</Button>
                                        </>
                                    ) : (
                                        <Button type="primary" onClick={() => {
                                            setOriginalTeacher(teacher); // 保存当前数据
                                            setIsEditing(true);
                                        }} style={{ marginLeft: "250px", marginTop: "10px" }}>编辑</Button>
                                    )}
                                </Space>
                            </div>
                        </div>
                    </TabPane>

                    {/* 修改密码界面 */}
                    <TabPane tab="修改密码" key="2">
                        <div style={{ height: '100%', display: 'flex', flexDirection: 'row', marginTop: '100px', marginLeft: '300px' }}>
                            <div style={{ width: '65%', display: 'flex', flexDirection: 'column' }}>
                                <Form layout="vertical">
                                    <Form.Item
                                        label="旧密码"
                                        validateStatus={oldPasswordError ? 'error' : ''}
                                        help={oldPasswordError}
                                    >
                                        <Input.Password
                                            placeholder="请输入旧密码"
                                            value={oldPassword}
                                            onChange={(e) => {
                                                setOldPassword(e.target.value);
                                                setOldPasswordError('');
                                            }}
                                            style={{ height: '30px', width: '60%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        label="新密码"
                                        validateStatus={newPasswordError ? 'error' : ''}
                                        help={
                                            <div>
                                                {newPasswordError && <div style={{ color: '#ff4d4f' }}>{newPasswordError}</div>}
                                                <div style={{ color: '#faad14', marginTop: '4px' }}>
                                                    建议：长度不小于8位，且包含大小写英文字母、数字和符号。
                                                </div>
                                            </div>
                                        }
                                    >
                                        <Input.Password
                                            placeholder="请输入新密码"
                                            value={newPassword}
                                            onChange={(e) => {
                                                setNewPassword(e.target.value);
                                                setNewPasswordError('');
                                            }}
                                            style={{ height: '30px', width: '60%' }}
                                        />
                                    </Form.Item>
                                    <Form.Item label="确认新密码">
                                        <Input.Password
                                            placeholder="请确认新密码"
                                            value={confirmPassword}
                                            onChange={(e) => setConfirmPassword(e.target.value)}
                                            style={{ height: '30px', width: '60%' }}
                                        />
                                    </Form.Item>
                                </Form>
                                <Space style={{ marginTop: 'auto', marginBottom: 24 }}>
                                    <Button type="primary" onClick={handlePasswordChange} style={{ marginLeft: "100px", marginTop: "20px" }}>保存</Button>
                                </Space>
                            </div>
                        </div>
                    </TabPane>
                </Tabs>
            </Card>
        </div >
    );
};

export default TeacherProfile;